<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>DinoTwitter - cull your friends list</title>
<!-- Source File -->
<!--CSS file (default YUI Sam Skin) -->
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.4.0/build/datatable/assets/skins/sam/datatable.css">

<style>
#loginInfo { border: solid #85D399;background-color:#78D5CD; width:220px;}
#followersTable { float:left; margin:20px;}
#logger { position: relative;float:right;margin:30px;}
/* customized css for scrolling */
.yui-dt-scrollable  {
    width:30em; /* SET OVERALL WIDTH HERE for ie (make sure columns add up to this total) */
    height:20em; /* SET HEIGHT HERE for ie */
}
.yui-dt-scrollbody {
    height:20em; /* SET HEIGHT HERE for non-ie */
    *height:auto; /* for ie */
}
.yui-dt-scrollable  thead {
    background:#696969; /*dark gray*/ /* ie needs a background color */
    color:#fff;
}

.yui-dt-scrollable th, .yui-dt-scrollbody td {
    width:20em;
}
#dateWindow { width:3.5em; }
#username { width:10em; }
</style>

<!-- Load the YUI Loader script: -->
<script src="http://yui.yahooapis.com/2.4.1/build/yuiloader/yuiloader-beta-min.js"></script>
<script type="text/javascript">

// Instantiate and configure Loader:
var loader = new YAHOO.util.YUILoader({

    // Identify the components you want to load.  Loader will automatically identify
    // any additional dependencies required for the specified components.
    require: ["event","base","reset","fonts","connection","button", "datatable"],

    // Configure loader to pull in optional dependencies.  For example, animation
    // is an optional dependency for slider.
    loadOptional: false,
	//filter: "DEBUG",
    // The function to call when all script/css resources have been loaded
    onSuccess: function() {
        dinotwitter.YUILoaded();
    }
});

// Load the files using the insert() method. The insert method takes an optional
// configuration object, and in this case we have configured everything in
// the constructor, so we don't need to pass anything to insert().
loader.insert();
/**
 * @author skoon
 */
var dinotwitter = {
    totalFriends : "",
	currentUsername: "",
	friends : new Array(),
	YUILoaded: function() {
		YAHOO.util.Event.onDOMReady(dinotwitter.init);
		//var logger = new YAHOO.widget.LogReader("logger");
	},
	init: function() {
			var subButtonAuth = new YAHOO.widget.Button("btnSubmitAuth");
		    subButtonAuth.on("click", dinotwitter.loadDataFromTwitter);
	},
	appendScriptTag : function(scriptSrc, id) {
	    var scriptTag = document.createElement("script");
		scriptTag.setAttribute("type", "text/javascript");
		scriptTag.setAttribute("charset", "utf-8");
		scriptTag.setAttribute("src", scriptSrc);
		scriptTag.setAttribute("id", id);
		var head = document.getElementsByTagName("head").item(0);
		head.appendChild(scriptTag);
	},
	getUsersTotalFriends : function() {
	  var sURL = "http://twitter.com/users/show/" + dinotwitter.currentUsername + ".json?callback=dinotwitter.parseTotalFriends";
      dinotwitter.appendScriptTag(sURL, "user" + dinotwitter.currentUsername);
	},
	parseTotalFriends : function(resultArray) {
	    dinotwitter.totalFriends = resultArray.friends_count;
		dinotwitter.getFriendsForUser();
	},
	loadDataFromTwitter: function() {
	    var username = document.getElementById("username").value;
	    if(username != dinotwitter.currentUsername) {
	        dinotwitter.currentUsername = username
	        dinotwitter.getUsersTotalFriends();
	    } else {
	        dinotwitter.populateDataSource();
	    };
	},
	getFriendsForUser : function() {
		var totalCalls = Math.round((dinotwitter.totalFriends/100));
	    if((dinotwitter.totalFriends % 100) > 0) { totalCalls++; };
	    YAHOO.log("dinotwitter.totalFriends=" + dinotwitter.totalFriends);
	    YAHOO.log("totalCalls=" + totalCalls);
	    for(i=1;i<=totalCalls;i++) {
	        if(i == totalCalls) {
	            dinotwitter.appendScriptTag("http://twitter.com/statuses/friends.json?callback=dinotwitter.twitterCallbackFinal&page=" + i, i);
	        } else {
	            dinotwitter.appendScriptTag("http://twitter.com/statuses/friends.json?callback=dinotwitter.twitterCallback&page=" + i, i);
	        };
        }	
	},
	twitterCallback : function(resultArray) {
		var tempArray = dinotwitter.friends.concat(resultArray);
		dinotwitter.friends = tempArray;
	},
	twitterCallbackFinal : function(resultArray) {
	    var tempArray = dinotwitter.friends.concat(resultArray);
		dinotwitter.friends = tempArray;
		dinotwitter.populateDataSource();
	},
	populateDataSource: function() {
        var daysToFilter = document.getElementById("dateWindow").value;
        var resultArray = dinotwitter.friends;
		var now = new Date();
		YAHOO.log(now, "filter");
		var filteredArray = new Array();
		YAHOO.log("resultArray.length=" + resultArray.length);
		for(i=0;i<resultArray.length;i++) {
		    var CreatedAt = new Date(resultArray[i].status.created_at);
		    YAHOO.log (CreatedAt, "filter");
		    var daysDiff = Math.floor(( now - CreatedAt) /  (1000 * 60 * 60 * 24));
		    YAHOO.log(now - CreatedAt,"filter");
		    YAHOO.log("daydDiff=" + daysDiff,"filter");
			if(daysDiff > daysToFilter) {
		        filteredArray.push(resultArray[i]);
			}
		};
		
		var ds =  new YAHOO.util.DataSource(filteredArray);
		ds.responseType= YAHOO.util.DataSource.TYPE_JSARRAY;
		ds.responseSchema = { fields: ["id","name",{key:"status", parser:function(data){return new Date(data.created_at)}}]};
		dinotwitter.populateDataTable(ds);

	},
	populateDataTable: function(dataSource) {
		var columns = [
		    {key:"id", label:"ID"},
		    {key:"name", label:"Name"},
			{key:"status", label:"Last Updated", formatter:"date", sortable:true},
			{label:"unfollow", formatter:YAHOO.widget.DataTable.formatButton}
		]
		var myDataTable = new YAHOO.widget.DataTable("followersTable", columns, dataSource, {sortedBy:{key:"status", dir: "desc"}, scrollable:true});		
		
		myDataTable.subscribe("buttonClickEvent", function(oArgs) {
			var record = myDataTable.getRecord(oArgs.target);
			dinotwitter.unfollow(record.getData("id"));
		});
	},
	unfollow: function(id) {
		var destroyUrl = "http://twitter.com/friendships/destroy/" + id + ".xml";
		var proxyIframe = document.getElementById("proxyCall");
		proxyIframe.src = destroyUrl;
	}	
};


</script>
	</head>
	<body class="yui-skin-sam">
		<div id="loginInfo">
		    Username:<input type="text"  id="username" size="15"><br/>
			Who hasn't updated in:<input type="text" id="dateWindow" value="30" size="5"> days<br/>
			<input type="button" id="btnSubmitAuth" value="Fetch" />
		</div>
		<div id="container">
			<div id="followersTable"></div>
			<div id="logger"></div>
		</div>
		<iframe id="proxyCall" src="" style="display:none;"></iframe>
	</body>
</html>
